<?php

namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use think\Loader;
class Order extends Controller{
    /****
     * Class register          	      订单评论
     * @$post['order_id']             订单id
     * @$post['courier_id']        	  快递员id
     * @$post['content']              类型：0=差评，1=一般，2=好评
     * @$post['serve_grade']          店铺评分
     * @$post['superior_id']          上级id
     * @$post['taste_grade']          味道评分
     * @$post['pack_grade']           包装评分
     * @$post['manner_grade']         服务评分
     * @$post['like']                 0=差，1=点赞
     * @$post['anonymity']            状态：0=匿名，1=不匿名
     * @$post['image']                评论图片

     * @date                	        2020/06/03 
     * @package application\index\controller\OrderComment
    */
    public function index(){  
      $post = input('post.');  
	  $order_number = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
      $data=[
        'mid'            =>$post['mid'],
        'product_id'     =>$post['product_id'],
        'total_price'    =>$post['total_price'],
        'pack'           =>$post['pack'],
        'coupon_id'      =>$post['coupon_id'],
		'payment'        =>$post['payment'],
        'type'    		 =>$post['type'],
        'shipping_fee'   =>$post['shipping_fee'],
        'orderid'        =>'ZTXY'.$order_number,
        'order_time'     =>time(),
        'status'         =>0,
        'site_id'        =>$post['site_id'],
		'courier_id'     =>$post['courier_id'],
		'user_id'        =>$post['user_id'],
		'content'        =>$post['content'], 
		'pid'			 =>$post['pid'],
      ];    
      $order= Db::name('order')->insert($data);
      if($order){
      	$order_find = Db::name('order')->where(['user_id'=>$post['user_id']])->order('id desc')->find(); 
         $arr = [
           'state'      => 1,
           'order_find'	=>$order_find,
           'message'    => "请求成功"
        ];
      }else{
        $arr = [
           'state'      => 0,
           'message'    => "请求成功"
        ];
      }
        return json($arr);
    }
	
	public function coupon(){  
		$user_id = input('user_id');
		$id = input('id');
		$coupon = Db::name('coupon')->where(['user_id'=>$user_id,'id'=>id])->find();
		$arr = [
           'state'      => 1,
           'message'    => "请求成功"
        ];
		return json($arr);
	}
	 /**
    *商家端订单
    **/
	public function manystore_check(){
      $mid = input('mid');
	  $status = input('status');
	  $order = Db::name('order a')->where(['mid'=>$mid])->field('product_id')->select();
		  
		$new_id_array = array();
		$new_id_array2 = array();
		
		  
	  foreach($order as $key => $value){
		  
		  $json = json_decode($value['product_id'],true);
		  
		  $new_id_array[$key] = $json[0]['id'];
		 
	  }
	  if(is_array($new_id_array) && count($new_id_array) > 0){
		  foreach($new_id_array as $key => $value){
			  if($status == 10){ 
					$shopro_goods = Db::name('shopro_goods a')
									->where(['a.id'=>$value])
									->join('order b','a.id = '.$value,'LEFT')
									->join('address c','c.id = b.site_id','LEFT')
									// ->join('courier d','d.id = b.courier_id','LEFT')
									// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
									->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
									->select();
					
					if($order){
						 $arr = [
						   'state'      	=> 1,
						   'shopro_goods'	=>$shopro_goods,
						];
					}else{
						$arr = [
						   'state'      => 0,
						   'order'      => ""
						];
					}
					
			  }else{
				  $shopro_goods = Db::name('shopro_goods a')
									->where(['a.id'=>$value,'b.status'=>$status])
									->join('order b','a.id = '.$value,'LEFT')
									->join('address c','c.id = b.site_id','LEFT')
									// ->join('courier d','d.id = b.courier_id','LEFT')
									// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
									->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
									->select();
					if($order){
						 $arr = [
						   'state'      	=> 1,
						   'shopro_goods'	=>$shopro_goods,
						]; 
					}else{
						$arr = [
						   'state'      => 0,
						   'order'      => ""
						];
					}
			  } 
		  }
					$new_id_array2[] = $arr;
		  
	  }
	  return json($new_id_array2);	  
    } 
	/**
    *查看商家端自动接单
    **/
	public function self_motion_check(){
		$mid = input('mid');
		$manystore = Db::name('manystore')->where(['id'=>$mid])->find();
		if($manystore){
			 $arr = [
			   'state'      => 1,
			   'manystore'	=>$manystore,
			   'message'    => "成功"
			];
		  }else{
			$arr = [
			   'state'      => 0,
			   'message'    => "失败"
			];
		  }
		return json($arr);
    }
     /**    
    *商家端自动接单
    **/
	public function self_motion(){
		$mid = input('mid');
		$self_motion = input('self_motion');
		$data = [
			'id' =>$mid,
			'self_motion' =>$self_motion
		];
		$manystore = Db::name('manystore')->update($data);
		if($manystore){
			 $arr = [
			   'state'      => 1,
			   'message'    => "接单成功"
			];
		  }else{
			$arr = [
			   'state'      => 0,
			   'message'    => "接单失败"
			];
		  }
		return json($arr);
    }
	 /**
    *商家端手动接单
    **/
     public function receiving_orders(){
     		$id = input('order_id');
     		$status = input('status');
     		$data = [
     			'id' =>$id,
     			'status' =>$status
     		];
     		$order = Db::name('order')->update($data);
     		if($order){
				$this->printer($id);
		         $arr = [
		           'state'      => 1,
		           'message'    => "接单成功"
		        ];
		      }else{
		        $arr = [
		           'state'      => 0,
		           'message'    => "接单失败"
		        ];
		      }
        	return json($arr);

     }
      /**
    *商家端同意退款
    **/
     public function agree_to_refund(){
     		$order_id = input('order_id');
     		$data = [
     			'id' =>$order_id,
     			'status' =>7
     		];
     		$order = Db::name('order')->update($data);
     		if($order){
		         $arr = [
		           'state'      => 1,
		           'message'    => "同意退款成功"
		        ];
		      }else{
		        $arr = [
		           'state'      => 0,
		           'message'    => "同意退款失败"
		        ];
		      }
        	return json($arr);

     }
      /**
    *商家端确认送出
    **/
     public function confirm_delivery(){
     		$order_id = input('order_id');
     		$data = [
     			'id' =>$order_id,
     			'status' =>3
     		];
     		$order = Db::name('order')->update($data);
     		if($order){
		         $arr = [
		           'state'      => 1,
		           'message'    => "确认送出成功"
		        ];
		      }else{
		        $arr = [
		           'state'      => 0,
		           'message'    => "确认送出失败"
		        ];
		      }
        	return json($arr);

     }
      /**
    *商家端拒绝退单
    **/
     public function agree_refund(){
     		$order_id = input('order_id');
		        $arr = [
		           'state'      => 1,
		           'message'    => "拒绝退单成功"
		        ];
        	return json($arr);

     }
      /**
    *商户端订单详情
    **/
      public function manystore_details(){
      		$order_id = input('order_id');
      		$shopro_goods = Db::name('order b')
					->where(['b.id'=>$order_id])
					->join('shopro_goods a','a.id =b.pid ','LEFT')
					->join('address c','c.id = b.site_id','LEFT')
					// ->join('courier d','d.id = b.courier_id','LEFT')
					// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
					->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
					->find();
			if($shopro_goods){
		         $arr = [
		           'state'      => 1,
		           'shopro_goods'	=>$shopro_goods,
		           'message'    => "成功"
		        ];
		      }else{
		        $arr = [
		           'state'      => 0,
		           'message'    => "失败"
		        ];
		      }
        	return json($arr);
      }
	  /**
    *骑手端订单
    **/
	public function courier_check(){
      $courier_id = input('courier_id');
	  $status = input('status');
	  $order = Db::name('order a')->where(['courier_id'=>$courier_id])->field('product_id')->select();
		  
		$new_id_array = array();
		$new_id_array2 = array();
		
		  
	  foreach($order as $key => $value){
		  
		  $json = json_decode($value['product_id'],true);
		  
		  $new_id_array[$key] = $json[0]['id'];
		 
	  }
	  if(is_array($new_id_array) && count($new_id_array) > 0){
		  foreach($new_id_array as $key => $value){
			  if($courier_id == null && $status == 2){ 
					$shopro_goods = Db::name('shopro_goods a')
									->where(['a.id'=>$value])
									->join('order b','a.id = '.$value,'LEFT')
									->join('address c','c.id = b.site_id','LEFT')
									// ->join('courier d','d.id = b.courier_id','LEFT')
									// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
									->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
									->select();
					
					if($order){
						 $arr = [
						   'state'      	=> 1,
						   'shopro_goods'	=>$shopro_goods,
						];
					}else{
						$arr = [
						   'state'      => 0,
						   'order'      => ""
						];
					}
					
			  }else{
				  $shopro_goods = Db::name('shopro_goods a')
									->where(['a.id'=>$value,'b.status'=>$status,'b.courier_id'=>$courier_id])
									->join('order b','a.id = '.$value,'LEFT')
									->join('address c','c.id = b.site_id','LEFT')
									// ->join('courier d','d.id = b.courier_id','LEFT')
									// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
									->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
									->select();
					if($order){
						 $arr = [
						   'state'      	=> 1,
						   'shopro_goods'	=>$shopro_goods,
						]; 
					}else{
						$arr = [
						   'state'      => 0,
						   'order'      => ""
						];
					}
			  } 
		  }
					$new_id_array2[] = $arr;
		  
	  }
	  return json($new_id_array2);	  
    }
	
	 /**
    *骑手端订单详情
    **/
      public function courier_details(){
      		$order_id = input('order_id');
      		$shopro_goods = Db::name('order b')
					->where(['b.id'=>$order_id])
					->join('shopro_goods a','a.id =b.pid ','LEFT')
					->join('address c','c.id = b.site_id','LEFT')
					// ->join('courier d','d.id = b.courier_id','LEFT')
					// ->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular,d.truename,d.phone as coupon_phone')
					->field('a.*,b.*,c.name,c.phone,c.dispatching,c.particular')
					->find();
			if($shopro_goods){
		         $arr = [
		           'state'      => 1,
		           'shopro_goods'	=>$shopro_goods,
		           'message'    => "成功"
		        ];
		      }else{
		        $arr = [
		           'state'      => 0,
		           'message'    => "失败"
		        ];
		      }
        	return json($arr);
      }

    /**
    *客户端订单  
    **/
	public function check(){
      $user_id = input('user_id');
	  $status = input('status');
	  if($status == 10){
		  $order = Db::name('order a')
			->where(['a.user_id'=>$user_id])
			->join('manystore b','a.mid = b.id')
			->field('a.id as order_id,a.product_id,a.total_price,a.status,b.nickname,b.door_photo_image,shipping_fee,pack,coupon_id')
			->select();
			if($order == null){
		        $arr = [
		           'state'      => 0,
		           'message'    => "无订单"
		        ];
				return json($arr);
		    }
        	
	  }else{
		  $order = Db::name('order a')
			->where(['a.user_id'=>$user_id,'a.status'=>$status])
			->join('manystore b','a.mid = b.id')
			->field('a.id as order_id,a.product_id,a.total_price,a.status,b.nickname,b.door_photo_image,shipping_fee,pack,coupon_id')
			->select();
			if($order == null){
		        $arr = [
		           'state'      => 0,
		           'message'    => "无订单"
		        ];
				return json($arr);
		    }
        	
	  }
	  
	  // 方法 1
	  // dump($order);exit;
		foreach($order as $k => $v){
		  $id_array = json_decode($v['product_id'],true);

		  $new_id_array = [];
			if(is_array($id_array) && count($id_array) > 0){
				foreach($id_array as $k1 => $v1){
				  $product_id = $v1['id'];
				  $new_id_array[] = Db::name('shopro_goods')->find($product_id);
				}
			}
		  $order[$k]['goods_list'] = $new_id_array;
		}
		  // echo json_encode($order);
		  // exit;
	  return json($order);	  
    }
	
	
	public function check_details(){
      $user_id = input('user_id');
	  $id = input('id');
		  $order = Db::name('order a')
			->where(['a.user_id'=>$user_id,'a.id'=>$id])
			->join('manystore b','a.mid = b.id')
			->field('a.product_id,a.total_price,a.status,b.nickname,b.door_photo_image,a.shipping_fee,a.pack,a.coupon_id,a.coupon_type,b.business_phone')
			->select();
		foreach($order as $k => $v){
		  $id_array = json_decode($v['product_id'],true);
		  $new_id_array = [];
			foreach($id_array as $k1 => $v1){
			  $product_id = $v1['id'];
			  $new_id_array[] = Db::name('shopro_goods')->find($product_id);	  
			}
		  $order[$k]['goods_list'] = $new_id_array;
		}
	  return json($order);	  
    }
    /***余额支付***/       
    public function pay(){    
     $user_id = input('user_id');
     $total_price = input('total_price');
     $id = input('id');
	 $coupon_id = input('coupon_id');
	 $integral = input('integral');
	 $type = input('type');
     $user = Db::name('user')->where(['id'=>$user_id])->find();
     if($user['money'] >= $total_price){  
		  if($type == 10){  
			  if($user['score'] >= $integral){
				  $integral_order = $user['score'] - $integral;
				  $money = $user['money'] - $total_price;
				  $data = [
						'money'=>$money,
						'score'=>$integral_order,
				  ];
			      Db::name('user')->where(['id'=>$user_id])->update($data);
				  Db::name('integral_order')->where(['id'=>$id])->update(['status'=>1]);
				  $data_integral = [
					'credits'	  =>$user['score'],
					'the_integral'=>$integral,
					'addtime'	  =>time(),
					'pid'		  =>$id,
					'user_id'	  =>$user_id,
					'type'		  =>0,
				  ];
				  Db::name('integral_log')->insert($data_integral);
				  $arr = [
					'state'   =>1,
					'message' =>'支付成功！'
				  ];
			  }else{
				$arr = [
					'state'   =>0,
					'message' =>'积分不足！'
				];  
			  }
			  return json($arr);
		  }else{
			$money = $user['money'] - $total_price;
			$score = $user['score'] + $total_price;		  
			$data = [
				'money'=>$money,
				'score'=>$score
			];
			Db::name('user')->where(['id'=>$user_id])->update($data);
			$order_self_motion = Db::name('order')->where(['id'=>$id])->find();
			$manystore = Db::name('manystore')->where(['id'=>$order_self_motion['mid']])->find();
			if($manystore['self_motion'] == 'yes'){
				Db::name('order')->where(['id'=>$id])->update(['status'=>2]);
				$this->printer($id);
			}else{
				Db::name('order')->where(['id'=>$id])->update(['status'=>1]);
			}
			Db::name('coupon')->where(['id'=>$coupon_id])->delete();
			$coupon_data=[
				'coupon_id'=>$coupon_id,
				'addtime'=>time(),
				'user_id'=>$user_id,
			];
			
			Db::name('coupon_log')->insert($coupon_data);
		  }
          $arr = [
            'state'   =>1,
            'message' =>'支付成功！'
          ];
     }else{
          $arr = [
            'state'   =>0,
            'message' =>'余额不足！'
          ];
     }
        return json($arr);
    }
	/**
	**打印机是否自动配置  
	**/  
	public function allocation(){
		$mid = input('mid');
		$allocation = input('allocation');
		$printer_find = Db::name('printer')->where(['store_id'=>$mid])->find();
		$data = [
			'id'=>$printer_find['id'],
			'allocation' => $allocation
		];
		$printer = Db::name('printer')->update($data);
		if($printer){
			$arr = [
				'state'   =>1,
				'message' =>'成功'
          ];
		}else{
			$arr = [
				'state'   =>0,
				'message' =>'失败'
			];
		}
		return json($arr);
	}
	/**
	*查看自动打印机状态
	**/
	public function printer_check(){
		$mid = input('mid');
		$printer = Db::name('printer')->where(['store_id'=>$mid])->find();
		$arr = [
			'state'   =>1,
			'printer' =>$printer
		];
		return json($arr);
	}
	/**
	*手动打印
	**/    
	public function operation(){
		$id = input('id');
		$order = Db::name('order')->where(['id'=>$id])->find();
		$address = Db::name('address')->where(['id'=>$order['site_id']])->find();
		$order_name = Db::name('order a')
			->where(['a.id'=>1])
			->join('shopro_goods b','find_in_set(b.id,a.pid)','LEFT')
			->select();
		$printer = Db::name('printer')->where(['store_id'=>$order['mid']])->find();
		$json = json_decode($printer['param'],true); 
		$new_id_array = array();
		Loader::import('printer.HttpClient#class',EXTEND_PATH);
		define('USER', $json[3]['content']);
		define('UKEY', $json[4]['content']);
		define('SN', $json[6]['content']);      
		define('IP','api.feieyun.cn');
		define('PORT',80);          
		define('PATH','/Api/Open/'); 
		$content = '<CB>测试打印</CB><BR>';
		$content .= "订单号：".$order['orderid']."<BR>";
		$content .= '名称　　　　　 单价  数量 金额<BR>';
		$content .= '--------------------------------<BR>';   
		foreach($order_name as $key => $value){
			$new_id_array['title'] = $value['title'];
			$new_id_array['price'] = $value['price'];
			$title = $new_id_array['title'];
			$price = $new_id_array['price'];
			$content .= "".str_pad($title,20," ")."".$price.'  10  100.0<BR>';
		}
		$content .= '--------------------------------<BR>';
		$content .= "备注：".$order['content']."<BR>";
		$content .= "包装费：".$order['pack']."<BR>";
		$content .= "配送费：".$order['shipping_fee']."<BR>";
		$content .= "合计：".$order['total_price']."元<BR>";
		$content .= "联系姓名：".$address['name']."<BR>";
		$content .= "联系电话：".$address['phone']."<BR>";
		$content .= "送货地点：".$address['dispatching'].$address['particular']."<BR>";
		$content .= "订餐时间：". date('Y-m-d H:i:s', $order['order_time'])."<BR>";
		$content .= '<QR>http://www.feieyun.com</QR>';
		$this->printMsg(SN,$content,1);
	}
	
	public function printer($id){
		$order = Db::name('order')->where(['id'=>$id])->find();
		$address = Db::name('address')->where(['id'=>$order['site_id']])->find();
		$order_name = Db::name('order a')
			->where(['a.id'=>1])
			->join('shopro_goods b','find_in_set(b.id,a.pid)','LEFT')
			->select();
		$printer = Db::name('printer')->where(['store_id'=>$order['mid']])->find();
		
		if($printer == null){
			$arr = [
            'state'   =>10006,
            'message' =>'请先配置打印机'
          ];
		}
		if($printer['allocation'] != 'open'){
			$arr = [
			'state'   =>10007,
			'message' =>'未开启自动打印'
			]; 
		   return json($arr);
		}
		$json = json_decode($printer['param'],true); 
		$new_id_array = array();
		Loader::import('printer.HttpClient#class',EXTEND_PATH);
		define('USER', $json[3]['content']);
		define('UKEY', $json[4]['content']);
		define('SN', $json[6]['content']);      
		define('IP','api.feieyun.cn');
		define('PORT',80);          
		define('PATH','/Api/Open/'); 
		$content = '<CB>测试打印</CB><BR>';
		$content .= "订单号：".$order['orderid']."<BR>";
		$content .= '名称　　　　　 单价  数量 金额<BR>';
		$content .= '--------------------------------<BR>';   
		foreach($order_name as $key => $value){
			$new_id_array['title'] = $value['title'];
			$new_id_array['price'] = $value['price'];
			$title = $new_id_array['title'];
			$price = $new_id_array['price'];
			$content .= "".str_pad($title,20," ")."".$price.'  10  100.0<BR>';
		}
		$content .= '--------------------------------<BR>';
		$content .= "备注：".$order['content']."<BR>";
		$content .= "包装费：".$order['pack']."<BR>";
		$content .= "配送费：".$order['shipping_fee']."<BR>";
		$content .= "合计：".$order['total_price']."元<BR>";
		$content .= "联系姓名：".$address['name']."<BR>";
		$content .= "联系电话：".$address['phone']."<BR>";
		$content .= "送货地点：".$address['dispatching'].$address['particular']."<BR>";
		$content .= "订餐时间：". date('Y-m-d H:i:s', $order['order_time'])."<BR>";
		$content .= '<QR>http://www.feieyun.com</QR>';
		$this->printMsg(SN,$content,1);
	}
	 /**  
   * [打印订单接口 Open_printMsg]  
   * @param  [string] $sn      [打印机编号sn]
   * @param  [string] $content [打印内容]
   * @param  [string] $times   [打印联数]
   * @return [string]          [接口返回值]
   */
	function printMsg($sn,$content,$times){
		$time = time();         //请求时间
		$msgInfo = array(
		  'user'=>USER,
		  'stime'=>$time,
		  'sig'=>$this->signature($time),
		  'apiname'=>'Open_printMsg',
		  'sn'=>$sn,
		  'content'=>$content,
		  'times'=>$times
		);
		$client = new \HttpClient(IP,PORT);
		if(!$client->post(PATH,$msgInfo)){
		  echo 'error';
		}else{
		  $result = $client->getContent();
		  // echo $result;
		}
	}
	  /**
	   * [signature 生成签名]
	   * @param  [string] $time [当前UNIX时间戳，10位，精确到秒]
	   * @return [string]       [接口返回值]
	   */
	function signature($time){
		return sha1(USER.UKEY.$time);//公共参数，请求公钥
	}


}
